package cn.jack.test.friendcircle;

import android.support.test.uiautomator.By;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObject2;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

/**
 * Created by chengyinggen on 2019/2/26.
 */
public class FriendCircleRequest extends IFriendCircle {

    private final static String WE_CHAT_PACKAGE = "com.tencent.mm";

    UiDevice mDevice;
    FriendCircle mFriendCircle;

    private boolean isStart;


    public FriendCircleRequest(UiDevice uiDevice) {
        mDevice = uiDevice;
        isStart = true;
        mFriendCircle = new FCClickFind(this);
    }

    @Override
    public void setState(FriendCircle friendCircle) {
        friendCircle.handAction(0);
    }

    @Override
    public void clickFind() {
        handleClick(TextView.class, "发现");
    }

    @Override
    public void clickFriendCircle() {
        handleClick(TextView.class, "朋友圈");
    }

    @Override
    public void clickLongSendMessage() {
        UiObject2 object = getUiObject(ImageButton.class, "com.tencent.mm:id/jy");
        if (null != object) {
            object.click(1500);
            object.recycle();
        }
        try {
            Thread.sleep(400);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        UiObject2 editObject = getUiObject(EditText.class, "com.tencent.mm:id/cqx");
        if (null != editObject) {
            editObject.setText("自动化测试测试测试!!!");
            editObject.recycle();
        }
    }

    @Override
    public void clickSend() {
        handleClick(Button.class, "发表");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        isStart = false;
    }

    private UiObject2 getUiObject(Class<?> clazz, String resourceId) {
        if (null != mDevice) {
            return mDevice.findObject(By.clazz(clazz).res(resourceId));
        }
        return null;
    }

    private void handleClick(Class<?> clazz, String name) {
        if (null != mDevice) {
            UiObject object = mDevice.findObject(new UiSelector().className(clazz).text(name));
            try {
                object.click();
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void request(int action) {
        mFriendCircle.handAction(action);
    }

    @Override
    public boolean isStart() {
        return isStart;
    }
}
